<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item label="策略名称:">
        <el-input v-model.trim="query.strategyName" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="策略创建人:">
        <el-input v-model.trim="query.createUser" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item :table-form-merge="2" label="创建时间:" prop="transactTime">
        <el-date-picker
          v-model="query.timeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :clearable="true"
        />
      </el-form-item>
      <template v-slot:btns>
        <el-button
          v-permission="[50501,1]"
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
      </template>
    </el-table-form>

    <div style="margin-bottom: 10px;" class="btn-group">
      <el-button
        v-permission="[50501,2]"
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="addDataForm"
      >新增</el-button>
    </div>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      v-loading="$loadingPlugin.fetchData"
      border
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      :row-class-name="tableRowClassName"
      custom-column
      @fetch="fetchData"
    />
    <el-dialog
      v-el-drag-dialog
      :title="dataForm.strategyCode?'编辑策略':'新增策略'"
      :visible.sync="visible"
      width="824px"
      @closed="reset"
    >
      <el-form ref="dataForm" class="form" :model="dataForm" :rules="rules" label-position="right" label-width="150px">
        <el-form-item label="自动派单策略名称:" prop="strategyName">
          <el-input v-model="dataForm.strategyName" />
        </el-form-item>
        <el-form-item label="添加自动派单策略:" prop="strategyType">
          <el-select v-model="dataForm.strategyType" multiple placeholder="请选择" style="width: 100%;" @change="chooseStrategyType">
            <el-option
              v-for="item in StrategyTypeMap"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="自动派单策略:" prop="orderCode">
          <div style="color: red;">自动派单按照优先自动派单策略的顺序进行派单，所有自动派策略都派单失败，派单失败的单子会进入自动派单失败页面，进行手动派单</div>
          <div class="strategyType-box">
            <div v-for="(item,index) in descList" :key="index" class="strategyType-item">
              <div style="display: inline-block; margin-right: 10px;">第{{ index+1 }}优先策略: {{ item }}</div>
              <el-button v-show="index>0" type="primary" @click="up(index)">上移</el-button>
              <el-button v-show="index+1<dataForm.strategyType.length" type="primary" @click="down(index)">下移</el-button>
              <el-button type="danger" @click="removeType(index)">删除</el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="自动派单时间:" prop="dispatchTime">
          <div style="color: red;">开启自动派单之后，系统会按照设置的自动派单时间段进行自动派单，自动派单时间段之前未派单的单子，也会进行自动派单</div>
        </el-form-item>
        <!-- <el-form-item label="" prop="startTime" label-width="0px" style="width: 220px;display: inline-block;margin-left: 150px;">
          <el-time-select
            placeholder="起始时间"
            v-model="dataForm.startTime"
            :picker-options="{
              start: '00:00',
              step: '00:01',
              end: '23:59'
            }">
          </el-time-select>
        </el-form-item>
        <div style="display: inline-block;">至</div>
        <el-form-item label="" prop="endTime" label-width="0px" style="width: 220px;display: inline-block;">
        <el-time-select
          placeholder="结束时间"
          v-model="dataForm.endTime"
          :picker-options="{
            start: '00:00',
            step: '00:01',
            end: '23:59',
            minTime: dataForm.startTime
          }">
        </el-time-select>
        </el-form-item> -->
        <el-form-item label="" prop="dispatchTime" label-width="0px" style="display: inline-block; width: 220px; margin-left: 150px;">
          <el-time-picker
            v-model="dataForm.dispatchTime"
            is-range
            value-format="HH:mm:ss"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围"
          />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="$loadingPlugin.del" type="danger" @click="cancel('dataForm')">
          取消
        </el-button>
        <el-button :loading="$loadingPlugin.success" type="primary" @click="sumbit('dataForm')">
          保存
        </el-button>
      </div>
    </el-dialog>
    <sendOrdersTacticsDetail ref="sendOrdersTacticsDetail" />
  </div>
</template>

<script>
  import {
    queryMap,
    strategyList,
    saveOrUpdate,
    deleteStrategy
  } from '@/api'
  import { formatColumnMap, parseTime } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import sendOrdersTacticsDetail from './sendOrdersTacticsDetail'
  export default {
    name: '',
    components: {
      sendOrdersTacticsDetail
    },
    data() {
      return {
        visible: false,
        StrategyTypeMap: [],
        descList: [],
        value1: [],
        dataForm: {
          strategyCode: null,
          strategyName: '',
          dispatchTime: [],
          strategyType: []
        },
        rules: {
          strategyName: [{ required: true, message: '请填写策略名称', trigger: 'blur' }],
          strategyType: [{ required: true, message: '请选择策略模式', trigger: 'change' }],
          dispatchTime: [{ required: true, message: '请选择派单时间', trigger: 'blur' }]
        },
        query: {
          timeRange: [],
          strategyName: '',
          createUser: '',
          createTime: '',
          createTimeEnd: ''
        },
        tableData: {
          data: []
        }
      }
    },
    computed: {
      column: function() {
        return [
          {
            type: 'index',
            align: 'center'
          },
          {
            prop: 'strategyCode',
            label: '自动派单策略ID',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openDetail(row)}>
              {row.strategyCode}
            </el-link>
          )
          },
          { label: '策略名称', prop: 'strategyName' },
          { label: '自动派单时间', prop: 'dispatchTime' },
          { label: '创建策略人', prop: 'createUser' },
          {
            label: '创建时间',
            prop: 'createTime',
            width: 140,
            render: (h, { row }) => (
            <span>
              {row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}')}
            </span>
          )
          },
          {
            label: '操作',
            className: 'action-col',
            width: 130,
            align: 'center',
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
              <div>
                  <el-link
                    v-permission={[50501, 3]}
                    underline={false}
                    size='mini'
                    onClick={() => this.openDetail(row, $index)}
                  >
                    详情
                  </el-link>
                  <el-link
                    v-permission={[50501, 4]}
                    underline={false}
                    size='mini'
                    onClick={() => this.edit(row, $index)}
                  >
                    编辑
                  </el-link>
                  <el-link
                    v-permission={[50501, 5]}
                    underline={false}
                    size='mini'
                    onClick={() => this.remove(row, $index)}
                  >
                    删除
                  </el-link>
              </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      await Promise.all([this.queryOptionsMap()])
      this.$nextTick(() => {
        this.$refs.lbTable.fetch()
      })
    },
    beforeDestroy() {
    },
    methods: {
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              if (key === 'timeRange') {
                if (obj['timeRange'].length > 0) {
                  query['createTime'] = parseTime(obj[key][0], '{y}-{m}-{d}')
                  query['createTimeEnd'] = parseTime(obj[key][1], '{y}-{m}-{d}')
                }
              } else {
                query[key] = obj[key]
              }
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query)
        }
        const res = await strategyList(query)
        this.tableData.data = res.data
        this.flexColumnWidth()
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'StrategyType' })
        ])
        this.StrategyTypeMap = res1.data // 派单策略枚举
      },
      async openDetail(row) {
        await this.$refs.sendOrdersTacticsDetail.open(row)
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 设置行类名
      tableRowClassName({ row }) {
        if (row.orderStatus === 7) {
          return 'danger-row'
        }
        return ''
      },
      reset() {
        this.$refs.dataForm.resetFields()
        this.descList = []
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      // 选择策略
      chooseStrategyType(val) {
        this.descList = []
        for (const i of val) {
          this.descList.push(formatColumnMap(this.StrategyTypeMap, 'value', i, 'desc'))
        }
      },
      // 上移
      up(index) {
        const i = this.descList.splice(index, index + 1)
        this.descList = [...i, ...this.descList]
        const j = this.dataForm.strategyType.splice(index, 1)
        this.dataForm.strategyType = [...j, ...this.dataForm.strategyType]
      },
      // 下移
      down(index) {
        const i = this.descList.splice(index, index + 1)
        this.descList = [...this.descList, ...i]
        const j = this.dataForm.strategyType.splice(index, 1)
        this.dataForm.strategyType = [...this.dataForm.strategyType, ...j]
      },
      // 删除策略
      removeType(index) {
        this.descList.splice(index, 1)
        this.dataForm.strategyType.splice(index, 1)
      },
      // 新增
      addDataForm() {
        this.dataForm = {
          strategyCode: null,
          strategyName: '',
          dispatchTime: ['00:00:00', '23:59:59'],
          strategyType: []
        }
        this.descList = []
        this.visible = true
      },
      // 取消
      cancel(formName) {
        this.$refs[formName].resetFields()
        this.descList = []
        this.visible = false
      },
      // 保存
      sumbit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const form = {
              strategyCode: this.dataForm.strategyCode,
              strategyName: this.dataForm.strategyName,
              dispatchTime: this.dataForm.dispatchTime.join('-'),
              strategyType: this.dataForm.strategyType.join(',')
            }
            // console.log(form)
            saveOrUpdate(form).then(res => {
              this.$notify({
                title: '提示',
                message: '添加成功',
                type: 'success',
                duration: 2000
              })
              this.visible = false
              this.$refs.lbTable.fetch()
            }).catch(err => {
              // this.$message.error(err.message)
              console.log(err)
              this.visible = false
            })
          } else {
            return false
          }
        })
      },
      // 删除
      remove(row, index) {
        this.$confirm('确定删除此条策略？', '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$message({
            message: '正在删除',
            duration: 0,
            iconClass: 'el-icon-loading'
          })
          deleteStrategy({ strategyCode: row.strategyCode }).then(() => {
            this.tableData.data.splice(index, 1)
            this.$refs.lbTable.fetch()
            this.$notify({
              title: '提示',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          }).finally(() => {
            loading.close()
          })
        }).catch(() => {})
      },
      // 编辑
      edit(row, index) {
        // console.log(row)
        let newStrategyType = row.strategyType.split(',')
        newStrategyType = newStrategyType.map(item => {
          return Number(item)
        })
        this.descList = []
        for (const i of newStrategyType) {
          this.descList.push(formatColumnMap(this.StrategyTypeMap, 'value', i, 'desc'))
        }
        const dataForm = {
          strategyCode: row.strategyCode,
          strategyName: row.strategyName,
          dispatchTime: row.dispatchTime.split('-'),
          strategyType: newStrategyType
        }
        this.$nextTick(() => {
          this.dataForm = dataForm
        })
        this.visible = true
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
/deep/ .el-table tr.danger-row {
  background: #ffdfdf;
}
.strategyType-box {
  width: 100%;
  padding: 20px;
  color: #fff;
  background-color: rgb(153, 153, 153);
  .strategyType-item {
    margin-bottom: 10px;
    &:last-child {
      margin-bottom: 0;
    }
  }
}
</style>
